Passed
Push — main ( 2e5b0c...2f5713 )
by Andrii
02:37
created

core.ts ➔ joinWithLead   A

Complexity

Conditions 4

Size

Total Lines 12
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 12
rs 9.85
c 0
b 0
f 0
cc 4
1
import type { ClassNamed, ClassHash } from "./defs"
2
import type { Falsy } from "./ts-swiss"
3
import { EMPTY_ARRAY } from "./consts"
4
import { stringifyClassNamed } from "./utils"
5
6
const {keys: $keys} = Object
7
8
export {
9
  wrapper,  
10
  resolver,
11
  joinWithLead
12
}
13
14
function wrapper<T>(
15
  destination: T,
16
  className: undefined | string
17
) {
18
  //@ts-expect-error
19
  destination["className"] = className
20
  
21
  return stringifyClassNamed(destination as T & ClassNamed)
22
}
23
24
function resolver(
25
  vocabulary: undefined | Record<string, ClassHash>,
26
  actions: Record<string, ClassHash | boolean>
27
) {
28
  const keys = $keys(actions)
29
30
  for (let i = keys.length; i--;) {
31
    const key = keys[i]
32
    , act = actions[key]
33
    
34
    //TODO #10 Clarify what behaviour to implement
35
36
    if (act !== undefined && !act) {
37
      // https://jsbench.me/q8kltjsdwy/
38
      //@ts-expect-error
39
      keys[i] = false
40
      continue
41
    }
42
43
    const hash = vocabulary?.[key]
44
    if (hash !== undefined)
45
      keys[i] = hash
46
    else if (typeof act === "string")
47
      keys[i] = act
48
  }
49
50
  // https://jsbench.me/9mklnonq0m
51
  const filtered = keys.filter(x => x)
52
53
  return filtered.length === 0 ? EMPTY_ARRAY : filtered
54
}
55
56
//TODO Consider returning `undefined` on empty string
57
function joinWithLead(value: Falsy|ClassHash, arr: undefined | string | readonly string[]) : string {
58
  const str1 = value || ""
59
  if (!(arr && arr.length))
60
    return str1
61
  
62
  const str2 = typeof arr === "string" ? arr : arr.join(" ")
63
  if (!str1)
64
    return str2
65
66
  return `${str1} ${str2}`
67
}
68